// pages/newUserGoodsList/index.js
let common_js = require("../../utils/common.js");
let url_js = require("../../utils/url.js");
let user_js = require("../../utils/user.js");
let cart_js = require("../../utils/cart.js");
let const_js = require("../../utils/const.js");
let page_js = require("../../utils/pageOptions.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let wxp = require("../../utils/wxp.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageScrollTop: 0,
    containerTouchmove: '',
    userInfo: null,
    newUserInfo: null, //新用户信息
    timerObj: {
      timerId: null,
      isEnd: false,
      endTime: '',
      item: null
    },
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    faviroteList: [],
    bgImgUr: url_js.imgUrl + "xrzx_page_bg.png",
    timeBgImgUr: url_js.imgUrl + "xrzx_page_coupon_bg.png",
    couponGg1ImgUr: url_js.imgUrl + "index_xr-bg1.png",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
  },

  onUnload: function () {
    this.clearTimer();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果是分享进来的，并且没有选择角色，进入角色选择页面
    if (page_js.pageOptionsInfo()) {
      //2.relauch
      wx.reLaunch({
        url: '../indexSearchShop/indexSearchShop'
      });
    }
  },

  //初始化数据
  initData: function (options) {
    //没有角色--->角色选择
    if (!user_js.hasRole()) {
      //1.save param
      let obj = {
        url: '../newUserGoodsList/index',
        param: ''
      }
      page_js.savePageOptionsInfo(obj);
      //2.relauch
      //*********跳转放在onshow
      return;
    } else {
      //有角色，展示页面
      this.initUnShareOptionsData(options);
      //2.获取数据
      this.getRemoteDatas();
    }
  },

  //初始化options数据
  initUnShareOptionsData: function (options) {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo
    });
  },

  // 获取数据
  getRemoteDatas() {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    }
    Promise.all([api.wxRequest(url_js.newUserActivityinfoUrl, data), api.wxRequest(url_js.newUserActivityProductListUrl, data)]).then(results => {
      this.handleNewUserData(results[0]);
      this.handleProcuteListData(results[1]);
      // 更多好货推荐
    }).catch(err => {
      common_js.log(err);
    });

  },

  //处理返回的新用户数据
  handleNewUserData(res) {
    if (!res.result) {
      wxp.showModal({
        title: '提示',
        content: '活动已结束',
        showCancel: false
      }).then(res => {
        //返回首页
        wx.switchTab({
          url: '/pages/index/index',
        })
      }).catch(err => {});
      return;
    }

    let sum = parseInt(res.result.couponPackageTitle) + parseInt(res.result.newUserCoupon.faceValue);
    res.result.sum = sum;
    this.setData({
      newUserInfo: res.result
    });
    //打开分享
    wx.showShareMenu({});
    // 开启定时器
    this.initTimerObj(res.result);
  },

  // 处理返回的更多好货推荐数据
  handleProcuteListData(res) {
    this.setData({
      faviroteList: res.result
    })
  },

  // 更多好多推荐
  //添加商品
  onAddGoods: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myAddGoods);
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  //查看登录状态，未登录直接跳转登录
  checkIsToLoginIndex: function () {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return false;
    }
    return true;
  },

  // 新人专项商品点击
  onNewUserGoodsAdd(e) {
    //添加购买
    if (!this.checkIsToLoginIndex()) return;

    let index = e.currentTarget.dataset.index;
    let item = this.data.newUserInfo.productList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
  },


  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  // 商品详情
  onNewUserGoodsItem(e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.newUserInfo.productList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 初始化
  initTimerObj(item) {
    if (item.expire <= 0) return;
    let tmpTimerObj = this.data.timerObj;
    if (item.expire > 0) {
      tmpTimerObj.endTime = new Date().getTime() + item.expire * 1000;
    }
    //set dasta
    this.setData({
      timerObj: tmpTimerObj
    });
    // 开启计时器
    this.countDownTimer();
  },
  // 计时器**********
  countDownTimer() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let tmpTimerObj = this.data.timerObj;
    let endTime = tmpTimerObj.endTime;
    let time = (endTime - newTime) / 1000;
    // 如果活动未结束，对时间进行处理
    let hmsObj = common_js.getHrMinSecBySecond(time);
    tmpTimerObj.item = hmsObj.item;
    tmpTimerObj.isEnd = hmsObj.isEnd;
    // 先清除计时器
    this.clearTimer();
    //1s调用一次
    let that = this;
    let timerId = setTimeout(function () {
      that.countDownTimer();
    }, 1000);
    tmpTimerObj.timerId = timerId;
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      timerObj: tmpTimerObj
    })
    // 清除
    if (tmpTimerObj.isEnd) {
      this.clearTimer();
    }
  },
  // 清除计时器
  clearTimer() {
    if (this.data.timerObj.timerId) {
      clearTimeout(this.data.timerObj.timerId);
      this.data.timerObj.timerId = null;
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return this.shareAppMessage();
  },

  //获取分享的AppMessage
  shareAppMessage: function () {
    let tmpPath = '/pages/newUserGoodsList/index';
    return {
      title: this.data.newUserInfo.shareTitle,
      path: tmpPath,
      imageUrl: this.data.newUserInfo.shareImg
    }
  },
})